/*
 * Copyright (C) 2009 Jonathan Azoff <jon@azoffdesign.com>
 *
 * This script is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2, or (at your option) any
 * later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 */

 // toAJAX v1.0.1 - A script that can be used to turn any page into an AJAX page
 // Usage: 	call $("selector").toAJAX() on any link to turn it into an AJAX link. The links you
 //         use toAJAX on must have a rel attribute defined so that the AJAX handler knows what
 //         to look for on the AJAX call.
 // Arguments: The toAJAX function currently only takes 1 argument, whch is a callback function
 // Returns: A jQuery object that represents the selected toAJAX links
 // Notes:	toAJAX works best with sites that already work without AJAX and only have content that
 //         changes in a distinct area or areas.

(function($) {

	// Preloader Image
	var preloader = $("<img/>").attr("alt", "loading...").attr("src", "./tracker/addons/images/preloader.gif");

	// XHR Object
	var xhr = null;

	// The toAJAX extension
	$.fn.toAJAX = function(callback)
	{
		// The actual worker routine, it does all of the AJAX stuff
		var handler = function()
		{
			var obj = $(this);
			var url = obj.attr("href") || obj.attr("src");
			var id = "#" + obj.attr("rel");
			var target = $(id);

			// if we have an id to load into and a link where we want the information from...
			if(url && id != "#" && xhr == null)
			{
				xhr = $.ajax({
					type: "GET",
					url: url,
					cache: false,
					complete: function(){
						if(callback) callback();
						xhr = null;
					},
					beforeSend: function(){
						target.empty().append(preloader);
					},
					error: function(){
						throw("toAJAX could not complete, an AJAX error ocurred.");
					},
					/*dataFilter: function(data){
						return $(data).filter(id).html();
					},*/
					success: function(data){
						target.html(data);
					}
				});
			}

			// make sure the link does not load
			return false;
		}

		return this.click(handler).keypress(handler);
	}

})(jQuery);
